package menus_api

import (
	"errors"
	"fmt"
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func (MenusApi) MenusDeleteView(c *gin.Context) {
	var re models.RemoveRequest

	err := c.ShouldBindJSON(&re)
	if err != nil {
		http.FailWithCode(http.ParamsError, c)
		return
	}
	var menuList []*models.MenuModel
	// 查询菜单是否存在数据库中
	count := common.DB.Debug().Find(&menuList, re.IdList).RowsAffected
	if count == 0 {
		http.FailWithMessage("菜单不存在", c)
		return
	}
	// 在删除数据库数据 使用事务
	if err = common.DB.Transaction(func(tx *gorm.DB) error {
		err = common.DB.Model(&menuList).Association("BannerImages").Clear()
		if err != nil {
			common.Log.Error(err.Error())
			return errors.New("删除关联图片失败")
		}
		common.DB.Delete(&menuList)
		return nil
	}); err != nil {
		common.Log.Error(err.Error())
		http.FailWithMessage("菜单删除失败", c)
		return
	}
	http.IsOkWithMessage(fmt.Sprintf("共删除 %d 个菜单", count), c)
}
